var express = require('express');
var router = express.Router();
var logger = require('../common/logger').logger.getLogger("user");
var mysql_query = require('../common/mysql');
var httpresult = require('../common/response');
const question_model = require("../models/question");
const chapter_model = require("../models/chapter");
var datafile_conf = require('../config').filedata;
var utils = require('../common/utils');
const fileUpload = require('express-fileupload');
router.use(fileUpload({
    limits: { fileSize: datafile_conf.size_limit},
}));

let msoffice_templater = require("../common/msoffice-templater");


router.post('/add', async function(req, res, next) {
    req.body.description = utils.remove_src_host(req.body.description);
    req.body.stem = utils.remove_src_host(req.body.stem);
    req.body.analysis = utils.remove_src_host(req.body.analysis);
    req.body.answer = utils.remove_src_host(req.body.answer);

    let [err, data] = await question_model.createQuestion(null, req.body.description, req.body.stem, req.body.analysis, req.body.answer, req.body.chapter_id, req.body.bank_id, req.body.count || 1);
    if (err) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(req.body));
});

router.post('/update', async function(req, res, next) {
    let course_id = req.body.course_id;
    if (req.body.bank_id) {
        var [error, data] = await mysql_query("select course_id from bank where bank_id = ?", [req.body.bank_id]);
        if (error) {
            logger.warn(error);
            return res.send(httpresult.sys_error(error));
        }
        if (data.length === 0) {
            return res.send(httpresult.trans_error("BANK_NOT_EXIST", "该试卷不存在"));
        }
        course_id = data[0].course_id;
    }
    req.body.description = utils.remove_src_host(req.body.description)
    req.body.stem = utils.remove_src_host(req.body.stem)
    req.body.analysis = utils.remove_src_host(req.body.analysis)
    req.body.answer = utils.remove_src_host(req.body.answer)
    var [error, data] = await mysql_query("update question set course_id = ?, description = ?, stem = ?, analysis = ?, answer = ?, type = ?, chapter_id = ?, count = ? where question_id = ?",
        [course_id, req.body.description, req.body.stem, req.body.analysis, req.body.answer, req.body.type, req.body.chapter_id || 0, req.body.count || 1, req.body.question_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/delete', async function(req, res, next) {
    var [error, data] = await question_model.destroy_question(req.question_id);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

// 文件上传接口
router.post('/export_word', async function (req, res) {
    try {
        if (!req.files || Object.keys(req.files).length === 0) {
            return res.send({"errno": 1, "message": "No files were uploaded."});
        }
        const template_content = req.files.file.data;

        let question_set = {};
        let err = null;
        if (req.body.hasOwnProperty("with_chapter") && req.body.with_chapter.toString() === "true") {
            [err, question_set] = await question_model.get_questions_with_chapter(req.body.course_id, req.body.question_ids);
        } else {
            [err, question_set] = await question_model.get_questions(req.body.course_id, req.body.question_ids);
        }
        if (err) {
            return res.send({"errno": 1, "message": err});
        }

        question_set["zk"] = "test";
        let opt = {
            delimiter: [ "{{", "}}"]
        }
        let docx_content = await msoffice_templater.render_docx(template_content, question_set, opt);
        res.writeHead(200, {
            "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "Content-Disposition": "attachment; filename='output.docx'"
        });
        res.write(docx_content);
        res.end();
        return;
    }
    catch (err) {
        logger.warn(err);
        return res.send(
            {
                "errno": 1, // 只要不等于 0 就行
                "message": err
            }
        )
    }
});

module.exports = router;
